//
//  ViewController.m
//  ImagePickers
//
//  Created by burning on 7/14/15.
//  Copyright (c) 2015 burning. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@property (assign, nonatomic) NSInteger remain;
@property (strong, nonatomic) NSMutableArray *selectedImageList;
@property (strong, nonatomic) QBImagePickerController *qbImagePickerController;
@property (strong, nonatomic) NSString *uploadApi;

@property (weak, nonatomic) IBOutlet UICollectionView *myCollection;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    self.remain = 5;
    self.selectedImageList = [[NSMutableArray alloc] init];
    self.uploadApi = @"http://localhost:3000/ios-upload";
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)pickImageButtonClick:(id)sender {
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"Pick Images From" delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:@"UIImagePicker", @"QBImagePicker", @"Other", nil];
    [actionSheet showFromBarButtonItem:nil animated:YES];
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    // NSLog(@"clickedButtonAtIndex:buttonIndex=%li", buttonIndex);
    if (buttonIndex == 1) {
        [self initQBImagePicker];
    }
}

- (void)initQBImagePicker {
    if (self.remain <= 0) {
        return;
    }
    
    self.qbImagePickerController = [[QBImagePickerController alloc] init];
    self.qbImagePickerController.delegate = self;
    self.qbImagePickerController.filterType = QBImagePickerControllerFilterTypePhotos;
    self.qbImagePickerController.allowsMultipleSelection = YES;
    self.qbImagePickerController.maximumNumberOfSelection = self.remain;
    
    
    [self presentViewController:self.qbImagePickerController animated:YES completion:nil];
}

- (void)qb_imagePickerController:(QBImagePickerController *)imagePickerController didSelectAsset:(ALAsset *)asset {
    NSLog(@"didSelectAsset %@", asset);
    [self.qbImagePickerController dismissViewControllerAnimated:YES completion:nil];
}

- (void)qb_imagePickerController:(QBImagePickerController *)imagePickerController didSelectAssets:(NSArray *)assets {
    [self.qbImagePickerController dismissViewControllerAnimated:YES completion:nil];
    
    self.remain -= assets.count;
    if (self.remain < 0) {
        self.remain = 0;
    }
    NSLog(@"select:%li - remain:%li", assets.count, self.remain);
    
    for (int i = 0; i < assets.count; i++) {
        ALAsset *asset = (ALAsset *)[assets objectAtIndex:i];
        UIImage *thumbnail = [[UIImage alloc] initWithCGImage:[asset thumbnail]];
        
        NSMutableDictionary *item = [[NSMutableDictionary alloc] init];
        [item setObject:thumbnail forKey:@"thumbnail"];
        [item setObject:@"YES" forKey:@"isUploading"];
        [self.selectedImageList addObject:item];
        
        ALAssetRepresentation *representation = [asset defaultRepresentation];
        UIImage *image = [UIImage imageWithCGImage:[representation fullResolutionImage] scale:representation.scale orientation:(UIImageOrientation)representation.orientation];

        NSData *data = UIImageJPEGRepresentation(image, 0.80);
        // NSLog(@"data length: %li", data.length);
        [self uploadImage:data successHandler:^(id responseObject) {
            [item setValue:@"NO" forKey:@"isUploading"];
            [self.myCollection reloadData];
        }];
    }
    // NSLog(@"selectedImageList %@", self.selectedImageList);
    
    [self.myCollection reloadData];
}

- (void)qb_imagePickerControllerDidCancel:(QBImagePickerController *)imagePickerController {
    NSLog(@"didCancel");
    // [self.qbImagePickerController dismissViewControllerAnimated:YES completion:nil];
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (self.remain > 0) {
        return self.selectedImageList.count + 1;
    } else {
        return self.selectedImageList.count;
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row < self.selectedImageList.count) {
        UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"imageCell" forIndexPath:indexPath];
        
        NSDictionary *item = [self.selectedImageList objectAtIndex:indexPath.row];
        UIImageView *imageView = (UIImageView *)[cell viewWithTag:1];
        UIImage *image = (UIImage *)[item objectForKey:@"thumbnail"];
        imageView.image = image;
        
        UILabel *tipLabel = (UILabel *)[cell viewWithTag:2];
        
        if ([[item valueForKey:@"isUploading"] isEqualToString:@"YES"]) {
            tipLabel.text = @"Uploading";
        } else {
            tipLabel.text = @"";
        }
        
        return cell;
    }
    else {
        UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"pickerCell" forIndexPath:indexPath];
        
        return cell;
    }
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == self.selectedImageList.count) {
        // [self pickImageButtonClick:nil];
        [self initQBImagePicker];
    }
}

- (void)uploadImage:(NSData *)imageData successHandler:(void (^)(id responseObject))success {
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSDictionary *parameters = @{@"foo": @"bar"};
    [manager POST:self.uploadApi parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [formData appendPartWithFileData:imageData name:@"NAME" fileName:@"FILE_NAME" mimeType:@"MIME_TYPE"];
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        // NSLog(@"operation: %@", operation);
        // NSLog(@"Success: %@", responseObject);
        if (success) {
            success(responseObject);
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
    }];
}

@end
